import uuid
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from datetime import datetime
from functools import partial
from datetime import datetime
from openai import OpenAI
import re
import json
import pymysql


#
# def schedule_task(hour, minute, day, month, task_function, *args, **kwargs):
#     """
#     Schedules a task to run at a specific time with additional arguments.
#
#     :param hour: The hour at which the task should run.
#     :param minute: The minute at which the task should run.
#     :param day: The day of the month on which the task should run.
#     :param month: The month in which the task should run.
#     :param task_function: The function to run at the specified time.
#     :param args: Additional positional arguments for the task function.
#     :param kwargs: Additional keyword arguments for the task function.
#     """
#     scheduler = BlockingScheduler()
#     # Use partial to pass additional arguments to the task function
#     partial_task_function = partial(task_function, *args, **kwargs)
#     scheduler.add_job(partial_task_function, CronTrigger(hour=hour, minute=minute, day=day, month=month, day_of_week='*'))
#     print(f"任务已经设置：{month}月{day}日 {hour}:{minute}执行。")
#     scheduler.start()














# 定义要执行的任务，接受额外的参数
def run_at_specific_time(message):
    print(f"记得{message['event']}哦")


def get_agent_task(question,user_id):
    client = OpenAI(
        api_key="sk-596LKhbDOLEwYtrNk2flYFZluVjgnHQXp5dlk2YYBAeavyk7",
        base_url="https://api.moonshot.cn/v1",
    )
    prompt_agent = """
#角色  
你是一个日程事件提取器 
#目标
根据用户输入解析事件摘要生成一句提醒用户的消息，并把时间格式解析为Cron格式,json输出
<示例>
"今天是星期六，现在时间是2024/03/23 23:05:00提醒我1分钟后看吴恩达深度学习课程"
输出： 
```JSON
{
"event":"看吴恩达深度学习课程",
"hour" = "23",
"minute" = "06"
"day" = "23"
"month" = "3"
}
```
<示例>

#原则
json输出，永远不要输出其他内容
"""
    # 获取当前日期和时间
    now = datetime.now()

    # 获取日期部分
    date_object = now.date()

    # 获取星期几的数字表示
    day_of_week = date_object.weekday()

    # 将数字转换为星期几的名称
    days = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]
    day_name = days[day_of_week]

    # 格式化日期字符串和当前时间
    prompt_user = f"今天是{date_object.strftime('%Y-%m-%d')} {day_name}，现在的时间是{now.strftime('%H:%M:%S')}"

    completion = client.chat.completions.create(
      model="moonshot-v1-8k",
      messages=[
        {"role": "system", "content": prompt_agent},
        {"role": "user", "content": prompt_user + question}
      ],
      temperature=0.3,
    )


    json_match = re.search(r'```JSON\s*(.*?)\s*```', completion.choices[0].message.content, re.DOTALL)

    # 如果找到匹配的JSON字符串，将其打印出来
    if json_match:
        json_string = json_match.group(1)
        # 设置任务执行时间
        json_string=json.loads(json_string)
        print("json_string",json_string)
        hour = json_string["hour"]
        minute = json_string["minute"]
        day = json_string["day"]
        month = json_string["month"]
        attach_time=month+","+day+","+hour+","+minute
        ctreat_at=datetime.now()
        task_id=str(uuid.uuid4())
        time = json_string["hour"] + ":" + minute + ":00"
        date="2024-"+json_string["month"]+"-"+json_string["day"]
        # 传递额外的参数给任务函数
        message = {
            "user_id": user_id,
            "task_id": task_id,
            "event": json_string["event"]
        }

        # 数据库连接配置，请根据实际情况进行修改
        config = {
            'host': 'localhost',
            'user': 'root',
            'password': '123456',
            'vector_db': 'agent',
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor
        }
        connection = pymysql.connect(**config)

        try:
            with connection.cursor() as cursor:
                # 准备要插入的数据
                data = {
                    'task_id': task_id,
                    'user_id': user_id,
                    'attach_time': attach_time,
                    'created_at': ctreat_at,
                    'event':json_string["event"],
                    'time':time,
                    'date':date
                }

                # 插入语句
                insert_query = """
                    INSERT INTO agent_tasks (task_id, user_id, attach_time, created_at,event)
                    VALUES (%(task_id)s, %(user_id)s, %(attach_time)s, %(created_at)s, %(event)s)
                """

                # 执行插入语句
                cursor.execute(insert_query, data)

                # 提交事务
                connection.commit()

                print("Data inserted successfully.")

            # 调用封装后的函数来安排任务，传递额外的参数
            # schedule_task(hour, minute, day, month, run_at_specific_time, message)
                return data
        except Exception as e:
            print(f"Error: {e}")
            connection.rollback()
            data = None
            return data
        finally:
            # 关闭数据库连接
            connection.close()


    else:
        print("No JSON string found.")
        data = None
    return data



